﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Runtime.Serialization.Json;
using System.IO;

namespace yeqw.FrameWork
{
    public  class JsonHelper
    {
        /// <summary>
        /// 从DatTable转成Json
        /// </summary>
        /// <param name="DT"></param>
        /// <returns></returns>
        public static string DataTableToJsonStr(DataTable DT)
        {
            StringBuilder result = new StringBuilder();
            result.Append("[");
            StringBuilder sbrow = new StringBuilder("");
            foreach (DataRow row in DT.Rows)
            {
              
                sbrow.Append("{");
                StringBuilder sbcol = new StringBuilder("");
                foreach (DataColumn col in DT.Columns)
                {
                     sbcol.AppendFormat("{0}:'{1}',",col.ColumnName,row[col]);
                }
                sbrow.Append(sbcol.ToString().TrimEnd(','));
                sbrow.Append("},");
            }
            result.Append(sbrow.ToString().TrimEnd(','));
            result.Append("]");
            return result.ToString();
        }
        /// <summary>
        /// HashTable转成最终的Json
        /// </summary>
        /// <param name="HT"></param>
        /// <returns></returns>
        public static string ListToJsonStr(Dictionary<string,string> HT)
        {
            StringBuilder result = new StringBuilder();
            //{totalProperty:10,root:[{id:'id',name:'name',descn:'descn'}]}
            result.Append("{");
            StringBuilder tmp = new StringBuilder();
            foreach (KeyValuePair<string,string> item in HT)
            {
                tmp.AppendFormat("{0}:{1},", item.Key, item.Value);

                
            }
            result.Append(tmp.ToString().TrimEnd(','));
            result.Append("}");
            return result.ToString();
        
        }

        public static  T parse<T>(string jsonString, string encodename)
        {
            var ms = new MemoryStream(Encoding.GetEncoding(encodename).GetBytes(jsonString));
            return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
        }
        
    }
}
